package zhuyun.code.datamanager.model

import android.app.Activity
import androidx.databinding.ObservableField
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProviders
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import zhuyun.code.datamanager.viewmodel.AccountViewModel
import java.lang.Exception
import java.sql.Connection
import java.sql.DriverManager
import java.util.concurrent.Flow
import io.reactivex.ObservableOnSubscribe


/**
 * @author: Administrator
 * @date: 2021/11/1
 */
class MysqlDatabase() {

    private var _data: ArrayList<Account?>? = null
    private var conn:Connection? = null
    private fun getConnection():Connection{
        return DriverManager.getConnection(url, user, password)
    }

    companion object {
        private const val url="jdbc:mysql://rdsz4kl5za13u8d0m3i8spublic.mysql.rds.aliyuncs.com:3306/chnspec?useUnicode=true&characterEncoding=UTF-8"
        private const val user = "spec3205722251"
        private const val password = "spec3205722251"
        private const val driverName = "com.mysql.jdbc.Driver"
        init {
            Class.forName(driverName)
        }
        private var mysqlDatabase:MysqlDatabase? = null
        fun getInstance():MysqlDatabase{
            if(mysqlDatabase == null){
                mysqlDatabase = MysqlDatabase()
            }
            return mysqlDatabase!!
        }
    }
    private var mAccountViewModel:AccountViewModel? = null
    fun loadData(callback: UpdateCallback) {
        _data = ArrayList()

        //mAccountViewModel = ViewModelProviders.of(context).get(AccountViewModel::class.java)

        Observable.create(ObservableOnSubscribe<Account> {
            conn = getConnection()
            val statement = conn?.createStatement()
            val sql = "select * from blog_users"
            val results = statement?.executeQuery(sql)
            if (results != null) {
                while (results.next()) {
                    val id = results.getLong("id")
                    val username = results.getString("username")
                    val password = results.getString("password")
                    val account = Account(id,username,password)
                    it.onNext(account)
                }
            }
            it.onComplete()
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object :
            Observer<Account> {

            override fun onNext(t: Account?) {
                _data!!.add(t)
            }

            override fun onError(e: Throwable?) {
                val i=0
            }
            override fun onComplete() {
                conn?.close()
                conn = null
               //mAccountViewModel?.data?.value = _data
                callback.update(_data!!)
            }

            override fun onSubscribe(d: Disposable?) {

            }
        })



    }

    fun addAccount(account: Account?, callback: AfterAddCallback) {
        Observable.create(ObservableOnSubscribe<Boolean> {
            conn = getConnection()
            val statement = conn?.createStatement();
            val sql = "insert into blog_users(username,password) values('${account?.username}','${account?.password}')"
            statement?.executeUpdate(sql)
            it.onNext(true)
            it.onComplete()

        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(object :Observer<Boolean>{
                override fun onComplete() {
                    conn?.close()
                    conn = null
                }

                override fun onSubscribe(d: Disposable?) {

                }

                override fun onNext(t: Boolean?) {
                    callback.update(true)
                }

                override fun onError(e: Throwable?) {
                    callback.update(false)
                }


            })
    }
}